from tortoise import fields, models
from tortoise.contrib.pydantic import pydantic_model_creator
from app.models.base.base import BaseModel


class ChatSession(BaseModel):
    """
    用户的一次完整对话会话（一次“新建对话”对应一条记录）
    用于支持恢复历史、分组展示、统计分析
    """

    id = fields.IntField(pk=True)
    user_id = fields.IntField(description="所属用户ID")
    title = fields.CharField(max_length=200, default="新对话", description="对话标题，可由 AI 自动生成")
    model = fields.CharField(max_length=50, default="qwen3:8b", description="本次对话使用的模型")
    
    class Meta:
        table = "chat_session"
        table_description = "用户AI对话会话"
        indexes = ["user_id", "is_deleted", "created_at"]

    def __str__(self):
        return f"ChatSession(id={self.id}, user={self.user_id}, title='{self.title}')"


class ChatHistory(BaseModel):
    """
    对话历史中的单条消息，归属于一个 ChatSession
    每次交互（用户提问或AI回复）都是一行
    """

    id = fields.IntField(pk=True)
    session = fields.ForeignKeyField(
        "models.ChatSession",
        related_name="messages",
        on_delete=fields.CASCADE,
        description="所属对话会话"
    )
    role = fields.CharField(max_length=10, description="角色: 'user' 或 'assistant'")
    content = fields.TextField(description="消息内容")
  

    class Meta:
        table = "chat_history"
        table_description = "AI对话历史消息"
        indexes = ["session_id", "role", "created_at"]

    def __str__(self):
        return f"ChatHistory(session={self.session_id}, role={self.role})"


